package day015.threadsocket;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:生产者和消费者
 * 不共享代码,共享资源
 * @date 2019/8/3 0003
 */
public class ProductAndCustomerDemo {
    public static void main(String[] args) {
        Box box = new Box();

        //创建生产
        Thread p = new Product(box);
        p.setName("生产者->");

        //消费者
        Thread c = new Customer(box);
        c.setName("消费者->");

        p.start();
        c.start();
    }
}

/**临界资源**/
class Box{//碗
    //鸡腿
    private int content;

    //判断box是否有内容
    private boolean has;//false

    public synchronized void setContent(int content) {
        if(has){
            try {
                wait();//进入到等待队列,等待消费者线程唤醒.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.content = content;
        //放了之后,碗里面是存在东西的
        has = true;

        notifyAll();
    }

    public synchronized int getContent() {
        if(has == false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //取完之后,碗里是没有东西
        has = false;
        notifyAll();
        return content;
    }
}
/***消费者*/
class Customer extends Thread{
    //private Box box = new Box();

    private Box box;

    public Customer(Box box){
        this.box = box;
    }

    @Override
    public void run() {
        while(true){
            System.out.println(Thread.currentThread().getName()+",取"+box.getContent()+"个");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**生产者者**/
class Product extends Thread{
    //private Box box = new Box();
    private Box box;

    private int i = 1;

    public Product(Box box){
        this.box = box;
    }

    @Override
    public void run() {
        while(true){

            System.out.println(Thread.currentThread().getName()+"->放"+i+"个!");
            box.setContent(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}